# _*_ coding:utf-8 _*_
# @File  : ruizy_file.py
# @Time  : 2022-03-26
# @Author: zizle
import random
import time
import uuid
import pathlib
import datetime
from fastapi import APIRouter, Form, UploadFile, File, Path, Header
from PIL import Image
from io import BytesIO
from typing import List
from global_constant import VARIETY
from hutool import security
from v1_all_api.all_response import AllResponse
from v1_all_api.all_utils import datetime_utils, char_utils
from configs import FILE_STORAGE
from db import FAConnection

file_api = APIRouter()


# 接口未使用
@file_api.post('/file/cache/')  # 文件上传
async def file_upload(file: UploadFile = Form(...)):
    # 使用uuid+时间戳的名称保存到服务器文件地址缓存起来
    uuid_str = ''.join(str(uuid.uuid4()).split('-'))
    filename = str(int(time.time() * 1000)) + uuid_str + pathlib.Path(file.filename).suffix
    month = datetime.datetime.today().strftime('%Y%m')
    middle_folder = pathlib.Path('cache/').joinpath(month)

    file_folder = pathlib.Path(FILE_STORAGE).joinpath(middle_folder)
    if not file_folder.exists():
        file_folder.mkdir(parents=True)
    filepath = file_folder.joinpath(filename)
    content = await file.read()  # 将文件保存到目标位置
    with open(filepath, "wb") as fp:
        fp.write(content)
    await file.close()
    file_url = str(pathlib.Path(middle_folder).joinpath(filename)).replace('\\', '/')
    # 转为Image对象
    # image = Image.open(BytesIO(content))
    # print(image)
    return AllResponse.create_successfully(data={'img_url': file_url}, msg='文件上传成功!')


# 批量pdf文件上传,按板块分类
@file_api.post('/{sec_name}/files/upload/')
async def module_files_upload(sec_name: str = Path(...), files: List[UploadFile] = File(...),
                              file_date: str = Form(None), ruizy_token: str = Header(...)):
    if sec_name == 'dailyReport':  # 日常报告
        file_date = datetime_utils.auth_datetime_string(file_date, f='%Y%m%d')
        if not file_date:
            return AllResponse.validate_error(msg='日期格式错误,接受YYYYMMDD类型')
        person = security.decrypt_access_token(ruizy_token)
        if not person:
            return AllResponse.no_authorization(msg='登录已过期，请重新登录.')
        folder = pathlib.Path(FILE_STORAGE).joinpath(f'Annexes/PeriodicReport/Daily/{file_date}')
        if not folder.exists():
            folder.mkdir(parents=True)
        save_data = []
        for f in files:
            uuid_str = chr(random.randint(97, 122)) + ''.join(str(uuid.uuid4()).split('-'))[1:]
            filename = str(int(time.time() * 1000)) + uuid_str + pathlib.Path(f.filename).suffix
            # 将文件保存下来，并添加记录
            filepath = folder.joinpath(filename)
            content = await f.read()  # 将文件保存到目标位置
            with open(filepath, "wb") as fp:
                fp.write(content)
            await f.close()
            # sql的数据对象
            title = char_utils.strQ2B(f.filename).replace('.pdf', '')
            sql_obj = {
                'file_date': file_date,
                'creator_id': person['uid'],
                'variety_en': ','.join([v for k, v in VARIETY.PERIODIC_REPORT.items() if k in title]),
                'file_type': 'DAILY',
                'title': title,  # 全角转半角
                'filepath': str(pathlib.Path(folder).joinpath(filename)).replace('\\', '/').replace(FILE_STORAGE, ''),
                'reading': 0
            }
            time.sleep(0.001)
            save_data.append(sql_obj)
        # 添加数据库记录
        sql = """
            INSERT INTO report_periodic_file
            (file_date,creator_id,variety_en,title,file_type,filepath)
            VALUES (%(file_date)s,%(creator_id)s,%(variety_en)s,%(title)s,%(file_type)s,%(filepath)s);
        """
        db_conn = FAConnection()
        count, _ = db_conn.insert(sql, param=save_data, many=True)
        if count == 0:
            for sf in save_data:
                saved_file = pathlib.Path(FILE_STORAGE).joinpath(sf['filepath'])
                if saved_file.exists():
                    saved_file.unlink()
        return AllResponse.operate_successfully(msg=f'上传文件成功.新增{count}个.')
    else:
        pass
    return AllResponse.operate_successfully()

